package com.jt.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jt.enums.modelEnums;
import com.jt.mapper.InventoryMapper;
import com.jt.mapper.LogsItemMapper;
import com.jt.mapper.LogsMapper;
import com.jt.pojo.Inventory;
import com.jt.pojo.Logs;
import com.jt.pojo.LogsItem;
import com.jt.service.LogsService;
import com.jt.util.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author jt
 * @date 2024/8/3 12:45
 */
@Service
public class LogsServiceImpl extends ServiceImpl<LogsMapper, Logs> implements LogsService {

    private LogsMapper logsMapper;

    private LogsItemMapper logsItemMapper;

    private InventoryMapper inventoryMapper;


    public LogsServiceImpl(LogsMapper logsMapper, LogsItemMapper logsItemMapper, InventoryMapper inventoryMapper) {
        this.logsMapper = logsMapper;
        this.logsItemMapper = logsItemMapper;
        this.inventoryMapper = inventoryMapper;
    }

    public Page<Logs> getList(Integer pageSize, Integer current){
        IPage page=new Page(current,pageSize);
        IPage logs = this.logsMapper.selectPage(page, new QueryWrapper<Logs>().orderByDesc("create_time"));
        return (Page<Logs>) logs;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveLog(Logs logs) {

        logs.setId(UuidUtils.randomUUID());
        logs.setCreateTime(new Date());
        this.logsMapper.insert(logs);
        if(logs.getLogsItem()!=null){
            logs.getLogsItem().forEach(res->{
                QueryWrapper<Inventory> wrapper =null;
                if(res.getLength()!=null){
                    wrapper = new QueryWrapper<Inventory>()
                            .eq("type", res.getType()).like("name", res.getLength());
                }
                else {
                    wrapper = new QueryWrapper<Inventory>()
                            .eq("type", res.getType());
                }
                res.setLogsId(logs.getId());
                this.logsItemMapper.insert(res);
                Inventory inventory = this.inventoryMapper.selectOne(wrapper);
                if(logs.getOperation().equals("0")){
                    //入库
                    inventory.setNum(inventory.getNum()+res.getNum());
                }
                if(logs.getOperation().equals("1")){
                    //出库
                    inventory.setNum(inventory.getNum()-res.getNum());
                }
                this.inventoryMapper.update(inventory,wrapper);
            });
        }


    }
}
